<template>
	<view class="container">
    <dm-ms :show="openInTime" @onClick="changeOne">
      <div class="offLineShop">当前店铺已打烊营业时间&nbsp;{{rTime}} <div style="    display: inline;
    border: 1px solid;
    padding: 5px;
    float: right;
    margin-right: 15rpx;
    margin-top: -15rpx;">换</div></div>
    </dm-ms>
		<view class="header">
			<!-- 搜索栏 begin -->
			<view class="search-box">
				<view class="search-input" @tap="showSearch=true"  :categories="categories">
					<image src="/static/images/common/search-icon.png" class="search-icon"></image>
					<view>搜索</view>
				</view>
			</view>
			<!-- 搜索栏 end -->
			<view class="center">
				<view class="store">
					<view class="title" @tap="selectLocation">
						<image :src="orderType == 'takein' ?
								'/static/images/common/star_normal.png' :
								'/static/images/order/order_icon_address.png'"
								class="left-icon" style="margin-top: -0.7rpx"/>
						<!-- 为了测试方便，这里使用静态店铺数据 -->
						<view class="address" style="margin-top: -10rpx">{{  currentPos.zzjgName }}</view>
						<image style="margin-top: -5rpx;" src="/static/images/common/black_arrow_right.png" class="right-icon"></image>
					</view>
					<!-- 外卖&自取switch begin -->
					<view class="buttons">
						<button type="default" class="button"
								:class="{active: orderType == 'takeout'}" plain
								hover-class="none" @tap="switchOrderType">
							自取
						</button>
						<button type="default" class="button"
								:class="{active: orderType == 'takein'}" plain
								hover-class="none" @tap="switchOrderType">
							外卖
						</button>
					</view>
					<!-- 外卖&自取switch end -->
				</view>
				<view  class="location">距离您{{ currentPos.juli || '正更新位置中'}}</view>
			</view>
			<!-- 滚动公告栏 begin -->
			<view class="notices">
				<swiper class="swiper" autoplay vertical :interval="3000" :duration="1000" circular>
					<swiper-item v-for="(notice, index) in notices" :key="index">
						<view class="swiper-item" @tap="function (){getSpuDto(notice)}">
							<image :src="notice.imgUrl" class="image"></image>
							<view class="content">{{ notice.title }}</view>
						</view>
					</swiper-item>
				</swiper>
				<view class="more">
					<text>更多</text>
					<image src="/static/images/common/gray_arrow_down.png" class="down-icon"></image>
				</view>
			</view>
		</view>
		<view class="main">
			<!-- 左侧菜单 begin -->
			<scroll-view class="menu-bar" scroll-y scroll-with-animation>
				<view class="wrapper">
					<view class="menu-item" @tap="handleMenuSelected(category.id)"
						  :class="{active: currentCategoryId == category.id}" v-for="(category, index) in categories" :key="index">
						<!-- <image :src="category.category_image_url" class="image" mode="widthFix"></image> -->
						<view class="title">
							<!-- <text v-if="category.icon" class="category-icon">{{ category.icon }}</text> -->
						{{ category.title }}</view>
					</view>
				</view>
			</scroll-view>
			<!-- 左侧菜单 end -->
			<!-- 右侧商品列表 begin -->
			<scroll-view class="product-section" scroll-y scroll-with-animation :scroll-top="productsScrollTop" @scroll="productsScroll">
				<view class="wrapper">
					<view id="ads" >
						<!-- 广告栏1 begin -->
						<swiper class="ads1" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" circular>
							<swiper-item v-for="(ad, index) in ads1" :key="index" >
								<image  :src="ad.imgUrl" class="w-100 adsImage" mode="widthFix" @tap="function (){getSpuDto(ad)}" ></image>
							</swiper-item>
						</swiper>
						<!-- 广告栏1 end -->
						<!-- 广告栏2 begin -->
						<swiper class="ads2" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" circular style="margin-top: -10rpx">
							<swiper-item v-for="(ad, index) in ads2" :key="index">
								<image :src="ad.imgUrl" class="w-100 adsImage"  mode="widthFix" @tap="function (){getSpuDto(ad)}"></image>
							</swiper-item>
						</swiper>
						<!-- 广告栏2 end -->
					</view>
					<!-- 商品 begin -->
					<view class="products-list" v-for="(category, index) in categories" :key="index" :id="`products-${category.id}`">
						<view class="category-name">
							{{ category.title }}
							<!-- <text class="category-tag">{{ category.tag }}</text> -->
						</view>
						<view class="products">
							<view class="product" v-for="(product, key) in category.spuDTOList" :key="key"
								@tap.stop="showProductDetailModal(product)">
								<image :src="product.img" mode="widthFix" class="image"></image>
								<view class="content">
									<view class="name">{{ product.title }}</view>
<!--									<view class="labels">-->
<!--										 <view class="label"-->
<!--										:class="{active: label.isHighlight !== '0'}"-->
<!--                           可加热-->
<!--										 v-for="label in product.coldProductTag" :key="label.id">{{ label.tagName }}</view>-->
<!--									</view>-->
								    <view class="labels">
								    	<view class="label" v-for="(tag, key) in getTagsList(product.tags)" >{{tag}}</view>
								    </view>
									<view class="description">{{ product.description }}</view>
									<view class="price">
										<view>￥{{ (product.price / 100).toFixed(2) }}</view>
										<actions :materials-btn="product.coldProductParameter.length"
												@materials="showProductDetailModal(product)"
												:number="productCartNum(product.id)"
												@add="handleAddToCart(product)"
												@minus="handleMinusFromCart(product)" />
									</view>
								</view>
							</view>
						</view>
					</view>
					<!-- 商品 end -->
				</view>
			</scroll-view>
			<!-- 右侧商品列表 end -->
		</view>

		<!-- 商品详情 modal begin -->
		<product-modal :product="product"
						:visible="productModalVisible"
						@cancel="closeProductDetailModal"
						@add-to-cart="handleAddToCartInModal"
		/>
		<!-- 商品详情 modal end -->
		<!-- 购物车栏 begin -->
		<cart-bar :cart="cart"
				  @add="handleAddToCart"
				  @minus="handleMinusFromCart"
				  @clear="clearCart"
				  @pay="pay"
		/>
		<!-- 购物车栏 end -->
		<search :show="showSearch" :categories="categories" @hide="showSearch=false" @choose="showProductDetailModal"></search>
		<nocity :show="!hasShop" :categories="categories" @hide="hasShop=false" @choose="showProductDetailModal"></nocity>
    <login-popup ref="loginPopup" @sureGrant="sureGrant"></login-popup>
    <div style="position: absolute;left:10px">
      <nx-can-use-coupon  id="ucoupon" ref="picCoupon" :isOpen="isOpen" :flag="true"  v-if="couponData.useList.length || couponData.stopList.length"
                          :discounts="couponDiscounts" :isShowCheck="true" :couponData="couponData" @submitCoupon="submitCoupon"
                          :noCouponShow="true"></nx-can-use-coupon>
    </div>
	</view>
</template>

<script>
	import {mapState, mapMutations} from 'vuex'
	import Actions from './components/actions/actions.vue'
	import CartBar from './components/cartbar/cartbar.vue'
	import ProductModal from './components/product-modal/product-modal.vue'
	import cartPopup from './components/cart-popup/cart-popup.vue'
	import Search from './components/search/search.vue'
	import Nocity from './components/nocity/nocity.vue'
  import dmMs from '../../components/dm-mask.vue'
  import loginPopup from '../my/components/login-popup.vue'

  export default {
		components: {
			Actions,
			CartBar,
			ProductModal,
			cartPopup,
			Search,
      Nocity,
      dmMs,
      loginPopup
		},
		data() {
			return {
				isClickCheck:true,
        isOpen:false,
        couponDiscounts: 0,
        couponData: {
          useList:[],
          stopList: []
        },
        rTime:'',
        openInTime:false,
				isHideToShow:false,
			    hasShop:true,
				dyTags:[],
				selectStore:null,
				categories: [],
				cart: [],
				product: {},
				currentCategoryId: 0,
				notices: [],
				ads1: [
				],
				ads2: [],
				productModalVisible: false,
				cartPopupShow: false,
				productsScrollTop: 0,
				showSearch: false,
				currentPos: {juli:"",zzjgName:'',jiedao:'',},
				currentSelectShopId:"",
        		currentcityShops:[],
				paramSpu:null,
			}
		},
		onShareAppMessage:function (e) {
		  console.log("abcdefg",e)
      if(e.target === undefined){
        return {
          title: this.$api.brandName,
          desc: '这个夏天我来陪你!',
          path: "/pages/index/index?oldUserUserId="+uni.getStorageSync("userId") //分享是获取分享人的UserId
        }
      }
			let {dataset}  = e.target
			console.log(dataset.shop)
			let shop = {}
			shop.unionType = 1;
			shop.unionValue=dataset.shop.id
			return {
				title: this.$api.brandName,
				desc: '这个夏天我来陪你!',
				path: "/pages/index/index?shopDetail="+encodeURIComponent(JSON.stringify(shop))+"&?oldUserUserId="+uni.getStorageSync("userId")
			}

		},
		async mounted() {
			  uni.setNavigationBarTitle({
				title: this.$api.customStoreageManage.getStorage("currentBrand").brandName
			  })
				await this.ifHasSelect()
				console.log("paramSpu",this.paramSpu)

				console.log("Onmouned")
				let zzjgId = await this.reloadMinShop()//重新加载最近的店铺
			    console.log("curentZZJG",this.currentPos.zzjgid)
				if(this.currentPos.zzjgid&&this.paramSpu !== null){
					this.getSpuDto(this.paramSpu)
				}
        if(uni.getStorageSync("userId")){
          console.log("UserId-----------",uni.getStorageSync("userId"))
          await this.getCouponsByShop()
          this.$nextTick(()=>{
            this.isOpen = true
          })
        }else{
          this.$api.ajax({
            url: "/web/app-order/check-auth",
            method: "post",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
             success:async (res) => {
              console.log(res.data);
              const { data } = res;
              if(data.status == 403||data.code==403){
                this.$refs['loginPopup'].open()
              }else{  //去查询当前店铺有没有优惠卷
                await this.getCouponsByShop()
                this.$nextTick(()=>{
                  this.isOpen = true
                })
                //this.$emit('pay')
              }

            }
          });
        }

                 //先获取当前店铺下有没有广告，如果有的话只加载当前店广告
				 this.getCurrentShopAD(zzjgId)
			    let advertisement = uni.getStorageSync('advertisement:'+this.$api.brandId)
				
			    let {t1=[],t6=[]} = advertisement;
			    this.notices = t6
      console.log("curentZZJG1",zzjgId)
          let afterFilter = t1.filter((item)=>{
            let {zzjgId} = item
            return this.currentPos.zzjgid==zzjgId
          })
           console.log("T111",afterFilter)
			    for(let [index,item] of afterFilter.entries()){
            if(index<afterFilter.length/2){
				    this.ads1.push(item)
				  } else{
				    this.ads2.push(item)
				 }
			   }
			  console.log("order",advertisement)


		},
		computed: {
			...mapState(['orderType', 'address']),
			productCartNum() {	//计算单个饮品添加到购物车的数量
				return id => this.cart.reduce((acc, cur) => {
						if(cur.id === id) {
							return acc += cur.number
						}
						return acc
					}, 0)
			}
		},
		async onShow(){
			if(this.isHideToShow){
				if(!this.ifHasSelect()){//如果缓存失效
					this.selectStore = null;
					this.reloadMinShop();
				}
				console.log("aaaaa")
			}
			// await this.getCouponsByShop()
			// this.$nextTick(()=>{
			//   this.isOpen = true
			// })
		},
		onHide(){
			this.isHideToShow = true
			console.log("离开了")
		},
		async onLoad(option) {
      this.$bus.$on('obtionCoupon', this.obtionCoupon)
			console.log("Onload")
			this.selectStore = null; //进页面之前先把选中的清空 避免判断失败
			//this.notices = await this.$api('notices')
			/**
			 * 判断是否有传递过来的商品信息
			 *
			 * //这里可能会有问题
			 * //TODO 稍后处理
			 */
			  if(option.shopDetail != null) {
				  console.log("option----------------->",decodeURIComponent(option.shopDetail))
				  let shopDetail = JSON.parse(decodeURIComponent(option.shopDetail));
				  this.paramSpu = shopDetail
			  }

       //说明有人是通过别人的分享进入到该页面的
      if(option.oldUserUserId != null) {
        console.log("option----------------->",decodeURIComponent(option.oldUserUserId))
        uni.setStorageSync("ouserId",decodeURIComponent(option.oldUserUserId))
        this.bindOAndNUser(option.oldUserUserId)
      }
		},
		methods: {
		async getCurrentShopAD(zzjgId){
			return new Promise(resolve => {
        //todo


      })
				
			},
      obtionCoupon(couponId){
		  if(this.isClickCheck){
			  this.isClickCheck = false
			  setTimeout(()=>{
				  console.log("----1111",couponId)
				  this.$api.ajax({
				    url: "/web/app-coupon/obtion-coupon",
				    data: {
				      couponId: couponId,
				      userId:  uni.getStorageSync("userId")
				    },
				    method: "post",
				    header: {
				      "Content-Type": "application/x-www-form-urlencoded"
				    },
				    success:(res) =>{
				      const { data,message } = res.data || {};
				      console.log("领取结果",data)
				  	if(data == undefined){
				  		uni.showToast({
				  		  title: message,
				  		  icon: 'none',
				  		  duration: 1000
				  		});
				  	}if(data=='erro'){
				        uni.showToast({
				          title: '亲您已经领取过,请勿重复领取',
				          icon: 'none',
				          duration: 1000
				        });
				      }
				  
				    }
				  });
				  this.isClickCheck = true
			  },500)

		}
      },
      getCouponsByShop(){
       // this.currentPos.zzjgid
        return new Promise(resolve => {
          this.$api.ajax({
            url: "/web/app-coupon/list-shop-coupons",
            data: {
              zzjgId: this.currentSelectShopId,
			   userId:  uni.getStorageSync("userId")
            },
            method: "post",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success:(res) =>{
              const { data } = res.data || {};
              console.log(data)
              this.couponList = data;
              this.couponData.useList = data;
              // this.$nextTick(()=>{
              //   this.$refs.picCoupon.$el.click();
              // })
              this.couponData.useList = this.couponData.useList.map((item) => {
                let obj = {
                  ...item,
                  checked: false, // 勾选
                  topRightTip: false, //右上角提示
                  bottomTip: false, // 底部提示
                  typeInfo: 'getObtion',
                  type:1
                }
                return obj
              })
              resolve(data)
         
              uni.hideLoading();
	

            }
          });
        })


      },
      sureGrant(newUid){
        console.log("newId",newUid)
        this.$api.ajax({
          url: "/web/app-coupon/mark-n-o",
          method: "post",
          data: {
            newUserId: newUid,
            oldUserId: uni.getStorageSync("ouserId")
          },
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success:(res) => {
            console.log("res",res)
          }
        });
        this.reloadMinShop();
      },
		  bindOAndNUser(olduid){
        this.$api.ajax({
          url: "/web/app-order/check-auth",
          method: "post",
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success:(res) => {
            console.log(res.data);
            const { data } = res;
            if(data.status == 403||data.code==403){
              this.$refs['loginPopup'].open()
            }else{
              //this.$emit('pay')
            }

          }
        });
      },
      async changeOne(target){
        let loca =  await this.$api.getWxLocation()
        console.log("aaa",loca.longitude)
        this.$api.ajax({
          url: "/web/app-zzjg/zzjg-list",
          data: {
            lat: loca.latitude,
            lng: loca.longitude,
            sheng: "河南省",
            shi: "郑州市",
            brandId: this.$api.brandId
          },
          method: "get",
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success:(res)=> {
            // console.log(res);
            const { data } = res
            console.log("dddd",data)
            this.currentcityShops = data.data
            uni.setStorageSync("currentcityShops",this.currentcityShops)
            this.$api.customStoreageManage.setStorage("currentcityShopsP", this.currentcityShops,1)
            uni.hideLoading()
            this.$nextTick(()=>{
              uni.navigateTo({
                url: "/pages/location/index"
                // url: "/pages/location/index?cityShops="+encodeURIComponent(JSON.stringify(this.currentcityShops))
              })
            })

          }
        });
      },
			 async reloadMinShop(){
        return new Promise((async resolve => {
          if(this.selectStore ==null) {
            console.log("来了么？")
            /**
             * 获取当前位置
             * 用于选择最近的门店
             */
            uni.showLoading()
            let loca =  await this.$api.getWxLocation()
            console.log("->" + JSON.stringify(loca))
            this.currentPos = loca
            console.log('当前位置的经度：' + this.currentPos.longitude);
            console.log('当前位置的纬度12：' + loca.latitude);
            /**
             * 获取最近一家店
             */
            // this.$api.ajax({
            //   url: "/web/map/qq/geo-coder-f",
            //   data: {
            //     location: loca.latitude + "," + loca.longitude,
            //   },
            //   method: "get",
            //   header: {
            //     "Content-Type": "application/x-www-form-urlencoded"
            //   },
            //   success: async (res) => {
            //      console.log(res);
            //     const {data} = res
            //     if (data.status === 0) {//说明请求成功
            //       let {result} = data.data
            //       let {ad_info, location} = result;
            //       let {province, city, district} = ad_info
            //       console.log("--->location",location)
            //       uni.hideLoading()
            //       let {lat, lng} = location
            //       //开始查当前城市最近的店
            //       await this.getMinShop(province, city, district, lat, lng);
            //     }
            //   }
            // });
            let data = await this.getGeoInfo(loca)
            let {result} = data.data
            let {ad_info, location} = result;
            let {province, city, district} = ad_info
            console.log("--->location",location)
            uni.hideLoading()
            let {lat, lng} = location
            let zzjgId = await this.getMinShop(province, city, district, lat, lng);
            resolve(zzjgId)
          }else{
            this.setOpenIN(this.selectStore)
            resolve(this.currentPos.zzjgid);
          }




        }))
			 },
       getGeoInfo(loca){
        return new Promise(resolve => {
          this.$api.ajax({
            url: "/web/map/qq/geo-coder-f",
            data: {
              location: loca.latitude + "," + loca.longitude,
            },
            method: "get",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: async (res) => {
              console.log(res);
              const {data} = res
              if (data.status === 0) {//说明请求成功
                let {result} = data.data
                let {ad_info, location} = result;
                let {province, city, district} = ad_info
                console.log("--->location",location)
                uni.hideLoading()
                let {lat, lng} = location
                //开始查当前城市最近的店
                resolve(data)
              }
            }
          });
        })
         /**
          * 获取最近一家店
          */



       },
       setOpenIN(item){
         this.openInTime = this.$api.isOpenInRangeTime(item)
         try{
           this.rTime = item.open_time.substr(0,item.open_time.length-3)+"-"+item.end_time.substr(0,item.end_time.length-3);
         }catch (e){
           console.log("erro",e)
           this.rTime = "09:00-23:00"
         }

       },
			 ifHasSelect(){
				// let isSelect = uni.getStorageSync("userSelect");
				let isSelect = this.$api.customStoreageManage.getStorage("userSelect");
				console.log("mmm",isSelect)
				if(isSelect!=null&&isSelect!=''){
					this.selectStore = isSelect;
          this.setOpenIN(this.selectStore)
					console.log("sssssss",this.selectStore)
					let {zzjg_name,jiedao,id,juli} = this.selectStore;
					this.currentPos.zzjgName = zzjg_name;
					this.currentPos.jiedao = jiedao;
					this.currentPos.zzjgid = id
					this.currentSelectShopId = id
					//this.jizhiConvert(juli)
					// console.log("tttt",this.$api.jizhiConvert(juli))
					this.$set(this.currentPos,"juli",this.$api.jizhiConvert(juli))
					this.getCategoriesSpuByZZJGID(id)
					return true
				}
				return false
			},
			getTagsList(tags){
				if(tags){
					return tags.split(",")
				}
				return [];
			},
			  /**
			   * unionType: 1
			   unionValue
			   * @param spu
			   */
      		getSpuDto(spu){
      			if(!spu){
      				return
				}
				console.log("222",spu)
				let {unionType,unionValue} = spu
				if(unionType == 1){ //说明关联的是商品
				  this.$api.ajax({
						url: "/web/app-product/detail",
						data: {
						    spuId: unionValue,
						    isBaiHuo:0,
							zzjgId :this.currentPos.zzjgid
						},
						method: "get",
						header: {
						  "Content-Type": "application/x-www-form-urlencoded"
						},
						success:(res)=> {
						  console.log("aaa",res.data.code);
						  const { data } = res
							if(data.code===20001){ //说明当前机构不存在该商品
								uni.showToast({
									icon: 'none',
									title: '当前商铺未上架该饮品'
								})
							}else{
								this.showProductDetailModal(data.data)
								console.log("Product",data)
							}


						}
					  })
				}





      },
		 	getShops(province,city,district,lat,lng){
				 this.$api.ajax({
					 url: "/web/app-zzjg/zzjg-list",
					 data: {
						 lat: lat,
						 lng: lng,
						 sheng: province,
						 shi: city ,
             brandId: this.$api.brandId
					 },
					 method: "get",
					 header: {
						 "Content-Type": "application/x-www-form-urlencoded"
					 },
					 success:(res)=> {
						 // console.log(res);
						 const { data } = res
						 console.log("dddd",data)
						 this.currentcityShops = data.data
						 uni.setStorageSync("currentcityShops",this.currentcityShops)
						 this.$api.customStoreageManage.setStorage("currentcityShopsP", this.currentcityShops,1)
						 this.$nextTick(()=>{
							 uni.navigateTo({
								 url: "/pages/location/index"
								 // url: "/pages/location/index?cityShops="+encodeURIComponent(JSON.stringify(this.currentcityShops))
							 })
						 })

					 }
				 });



			},

		  	getMinShop(province,city,district,lat,lng){
            return new Promise(resolve => {
              let flag =  this.$api.customStoreageManage.getStorage("currentcityShopsP")
              console.log("thisFlag",flag)
              if(flag ==undefined||flag == null ||flag == ''){
                this.$api.ajax({
                  url: "/web/app-zzjg/zzjg-list",
                  data: {
                    lat: lat,
                    lng: lng,
                    sheng: province,
                    shi: city,
                    brandId: this.$api.brandId
                  },
                  method: "get",
                  header: {
                    "Content-Type": "application/x-www-form-urlencoded"
                  },
                  success:async (res)=> {
                    // console.log(res);
                    const { data } = res
                    console.log("dddd",data)
                    this.currentcityShops = data.data
                    uni.setStorageSync("currentcityShops",this.currentcityShops)
                    this.$api.customStoreageManage.setStorage("currentcityShopsP", this.currentcityShops, 1)
                    if(data.data.length<=0){ //说明当前城市没有店铺
                      this.hasShop = false;
                      return
                    }
                    this.hasShop = true;
                    for(let jg of data.data){
                      let {zzjg_name,jiedao,juli,id} = jg
                      this.currentPos.zzjgName = zzjg_name;
                      this.currentPos.jiedao = jiedao;
                      this.currentPos.zzjgid = id
                      this.currentSelectShopId = id
                      console.log("watchParam",jg)
                      this.getSpuDto(this.paramSpu)
                      this.paramSpu = null
                      //this.jizhiConvert(juli)
                      // console.log("tttt",this.$api.jizhiConvert(juli))
                      this.$set(this.currentPos,"juli",this.$api.jizhiConvert(juli))
                      this.$api.customStoreageManage.setStorage("userSelect",jg,5)
                      //根据组织机构获取当前机构下的所有分类与商品商品
                      await this.getCategoriesSpuByZZJGID(id)
                      this.setOpenIN(jg)
                      break; //只取第一条也就是最近的一个店铺 然后跳出循环
                    }
                    uni.hideLoading()
                    resolve(this.currentPos.zzjgid)
                  }
                });
              }else{
                for(let jg of flag){
                  this.$api.customStoreageManage.setStorage("userSelect",jg,5)
                  let {zzjg_name,jiedao,juli,id} = jg
                  this.currentPos.zzjgName = zzjg_name;
                  this.currentPos.jiedao = jiedao;
                  this.currentPos.zzjgid = id
                  this.currentSelectShopId = id
                  this.getSpuDto(this.paramSpu)
                  this.paramSpu = null
                  this.getCategoriesSpuByZZJGID(id)
                  //this.jizhiConvert(juli)
                  // console.log("tttt",this.$api.jizhiConvert(juli))
                  this.$set(this.currentPos,"juli",this.$api.jizhiConvert(juli))
                  break; //只取第一条也就是最近的一个店铺 然后跳出循环
                }
                resolve(this.currentPos.zzjgid)
              }
            })




		  },
			async getCategoriesSpuByZZJGID(zzjgId){
      			console.log("zzjgId",zzjgId)
        return new Promise(resolve => {
           this.$api.ajax({
            url: "/web/app-category/category-list",
            // method: "post",
            data: {
              zzjgId
            },
            success: (res) => {
              const { data } = res.data || {};
              const { items } = data || {};
              console.log("abc",data)
              this.categories = data
              this.currentCategoryId = this.categories.length && this.categories[0].id
              this.$nextTick(() => this.calcSize())
              uni.hideLoading()
              resolve(true)
            }
          });
        })




				// this.categories = (await this.$api('categories')).data || [];
				// console.log("---->",this.categories)
				// this.currentCategoryId = this.categories.length && this.categories[0].id
				// this.$nextTick(() => this.calcSize())
			},
			// selectLocation 跳转到选择门店页面
			async selectLocation() {
				let flag =  this.$api.customStoreageManage.getStorage("currentcityShopsP")
				console.log("thisFlag",flag)
				if(flag ==undefined||flag == null ||flag == '') {
          let loca = await this.$api.getWxLocation();
          console.log("->" + JSON.stringify(loca))
          console.log('当前位置的经度：' + loca.longitude);
          console.log('当前位置的纬度12：' + loca.latitude);
          /**
           * 获取最近一家店
           */
          this.$api.ajax({
            url: "/web/map/qq/geo-coder-f",
            data: {
              location: loca.latitude + "," + loca.longitude,
            },
            method: "get",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: (res) => {
              // console.log(res);
              const {data} = res
              if (data.status === 0) {//说明请求成功
                let {result} = data.data
                let {ad_info, location} = result;
                let {province, city, district} = ad_info
                console.log(location)

                let {lat, lng} = location
                //开始查当前城市最近的店
                this.getShops(province, city, district, lat, lng);

              }


            }
          });

        }else{
					uni.navigateTo({
						url: "/pages/location/index"
						// url: "/pages/location/index?cityShops="+encodeURIComponent(JSON.stringify(this.currentcityShops))
					})
				}

			},
			...mapMutations(['SET_ORDER_TYPE']),
			switchOrderType() {
				if(this.orderType === 'takein') {
					uni.navigateTo({
						url: '/pages/addresses/addresses'
					})
				} else {
					this.SET_ORDER_TYPE('takein')
				}
			},
			handleAddToCart(product) {	//添加到购物车
      			console.log("product",product)
				const index = this.cart.findIndex(item => {
					if(product.materials_text) {
						// 商品是同一个，且规格也是同一个
						return (item.id == product.id) && (item.materials_text == product.materials_text)
					} else {
						return item.id === product.id
					}
				})

				if(index > -1) {
					this.cart[index].number += (1)
					return
				}

				this.cart.push({
					// id: product.productId,
					// // cate_id: product.category_id,
					// productName: product.productName,
					// price: product.price,
					// number: 1,
					// image: product.icon,
					// is_single: product.spuDTOList,
					...product,
					zzjgId:this.currentSelectShopId,
					number: product.number || 1,
					is_single: product.specificationList,
					materials_text: product.materials_text || ''
				})
			},
			handleMinusFromCart(product) { //从购物车减商品
				let index
				if(product.is_single) {
				   index = this.cart.findIndex(item => item.id == product.id)
				} else {
				   index = this.cart.findIndex(item => (item.id == product.id) && (item.materials_text == product.materials_text))
				}
				this.cart[index].number -= 1
				if(this.cart[index].number <= 0) {
					this.cart.splice(index, 1)
				}
			},
			showProductDetailModal(product) {
      			console.log("asdfsadfsadfsdaf1")
				this.product = product
				this.productModalVisible = true
			},
			handleAddToCartInModal(product) {
				this.handleAddToCart(product)
				this.closeProductDetailModal()
			},
			closeProductDetailModal() {
				this.productModalVisible = false
				// this.product = {}
			},
			openCartDetailsPopup() {
				this.$refs['cartPopup'].open()
			},
			clearCart() {
				this.cart = []
			},
			handleMenuSelected(id) {
				this.productsScrollTop = this.categories.find(item => item.id == id).top
				this.$nextTick(() => this.currentCategoryId = id)
			},
			productsScroll({detail}) {
				const {scrollTop} = detail
				let tabs = this.categories.filter(item=> item.top <= scrollTop).reverse()
				if(tabs.length > 0){
					this.currentCategoryId = tabs[0].id
				}
			},
			calcSize() {
				let h = 0
				let view = uni.createSelectorQuery().select('#ads')
				view.fields({
					size: true
				}, data => {
					h += Math.floor(data.height)
				}).exec()

				this.categories.forEach(item => {
					let view = uni.createSelectorQuery().select(`#products-${item.id}`)
					view.fields({
						size: true
					}, data => {
						item.top = h
						h += Math.floor(data.height)
						item.bottom = h
					}).exec()
				})
			},
			pay() {
				/**
				 * 设置了购物车缓存
				 */
				uni.setStorageSync('cart', this.cart)

				uni.navigateTo({
					url: '/pages/pay/pay?shop='+encodeURIComponent(JSON.stringify(this.currentPos))
				})
			}
		}
	}
</script>

<style lang="scss">
	@import './index.scss';
  .offLineShop{
    display: inline-block;
    position: absolute;
    bottom: 10rpx;
    z-index: 100;
    color: white;
    border: 1px solid;
    width: 100%;
    padding: 20px;
    border-radius: 15rpx;
  }
	.adsImage{
		max-height: 300rpx;
		border-radius: 15rpx;
	}
	.container{
		.center{
			.location{
				margin-left: -0.4rem;
			}
			.store{
				.title{
					margin-left: -0.8rem;
				}
			}
		}
	}
  .products{
    .product{
      margin-bottom: 25px;
      .image{
        height: 100px!important;
        border-radius: 20rpx;

      }
      .content{
        height: 100px;
        margin-left: 12px;
        .labels{
          .label{

          }
        }
      }
    }
  }
</style>
